package com.java.core.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileUtils {

	/**
	 * 获取文件二进制
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static byte[] getFileBinary(HttpServletRequest request, String name) {
		MultipartFile file = null;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			file = multipartRequest.getFile(name);
			if (file.getSize() > 0) {
				return file.getBytes();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 下载
	 * 
	 * @param request
	 * @param binary
	 * @throws IOException
	 */
	public static void download(HttpServletResponse response, String filename,
			byte[] binary) throws IOException {
		// 设置header
		response.reset();
		response.setContentLength(binary.length);
		response.setHeader("content-disposition", "attachment;filename=\""
				+ URLEncoder.encode(filename, "UTF-8") + "\"");
		response.setHeader("connection", "close");
		OutputStream out = response.getOutputStream();
		out.write(binary);
	}
}
